<template>
  <view class="room-edit-container">
    <view class="page-header">
      <text class="page-title">编辑房间</text>
      <text class="page-subtitle">赛程: {{ scheduleName }}</text>
    </view>

    <view v-if="loading" class="loading-container">
      <view class="loading-spinner"></view>
      <text>加载中...</text>
    </view>

    <view v-else class="form-section">
      <view class="form-item">
        <text class="form-label">房间名称</text>
        <input 
          class="form-input" 
          v-model="formData.name" 
          placeholder="请输入房间名称"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">房主</text>
        <input 
          class="form-input" 
          v-model="formData.owner" 
          placeholder="请输入房主ID"
        />
      </view>
      
      <view class="form-item">
        <text class="form-label">比赛时间</text>
        <picker 
          mode="date" 
          :value="matchDate" 
          @change="onDateChange"
          class="form-picker"
        >
          <view class="picker-text">{{ matchDate || '请选择比赛日期' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">房间状态</text>
        <picker 
          mode="selector" 
          :range="statusOptions" 
          :value="statusIndex" 
          @change="onStatusChange"
          class="form-picker"
        >
          <view class="picker-text">{{ statusOptions[statusIndex] || '请选择房间状态' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">获胜模式</text>
        <picker 
          mode="selector" 
          :range="winModelOptions" 
          :value="winModelIndex" 
          @change="onWinModelChange"
          class="form-picker"
        >
          <view class="picker-text">{{ winModelOptions[winModelIndex] || '请选择获胜模式' }}</view>
        </picker>
      </view>
      
      <view class="form-item">
        <text class="form-label">开始类型</text>
        <picker 
          mode="selector" 
          :range="startTypeOptions" 
          :value="startTypeIndex" 
          @change="onStartTypeChange"
          class="form-picker"
        >
          <view class="picker-text">{{ startTypeOptions[startTypeIndex] || '请选择开始类型' }}</view>
        </picker>
      </view>
    </view>
    
    <view class="form-actions">
      <button class="cancel-btn" @click="goBack">取消</button>
      <button class="submit-btn" @click="updateRoom" :disabled="submitting">
        {{ submitting ? '更新中...' : '更新房间' }}
      </button>
    </view>
  </view>
</template>

<script setup>
import { ref } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import { MatchRoomAPI } from '@/api/battle.js'

const scheduleId = ref('')
const scheduleName = ref('')
const roomId = ref('')
const loading = ref(false)
const submitting = ref(false)

const formData = ref({
  name: '',
  owner: '',
  matchTime: Date.now(),
  status: 1,
  winModel: 1,
  startType: 1
})

const matchDate = ref('')
const statusIndex = ref(0)
const winModelIndex = ref(0)
const startTypeIndex = ref(0)

const statusOptions = [
  '等待',
  '准备',
  '倒计时',
  '开始比赛',
  '结束比赛',
  '暂停',
  '取消/终止',
  '异常'
]

const winModelOptions = [
  '一回合 抢1分',
  '三回合 抢2分',
  '五回合 抢3分',
  '高分',
  'BO3',
  'AO5',
  'BAO5',
  '时间短',
  '步数短',
  '距离长',
  '五局（抢3） 五回合（抢3）'
]

const startTypeOptions = [
  '定时开赛',
  '手动开赛',
  '人满即开'
]

const fetchRoomData = async () => {
  if (!roomId.value) return
  
  loading.value = true
  try {
    const result = await MatchRoomAPI.page({
      matchRoomId: roomId.value,
      pageNum: 0,
      pageSize: 1
    })
    
    if (result.code === 0 && result.data?.list?.length > 0) {
      const room = result.data.list[0]
      formData.value = {
        name: room.name || '',
        owner: room.owner || '',
        matchTime: room.matchTime || Date.now(),
        status: room.status || 1,
        winModel: room.winModel || 1,
        startType: room.startType || 1
      }
      
      statusIndex.value = (room.status || 1) - 1
      winModelIndex.value = (room.winModel || 1) - 1
      startTypeIndex.value = room.startType || 1
      
      if (room.matchTime) {
        const date = new Date(room.matchTime)
        matchDate.value = date.toISOString().split('T')[0]
      }
    }
  } catch (error) {
    console.error('获取房间数据失败:', error)
    uni.showToast({
      title: '获取房间数据失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

onLoad((options) => {
  if (options.roomId) {
    roomId.value = options.roomId
  }
  if (options.scheduleId) {
    scheduleId.value = options.scheduleId
  }
  if (options.scheduleName) {
    scheduleName.value = decodeURIComponent(options.scheduleName || '')
  }
  
  fetchRoomData()
})

const onDateChange = (e) => {
  matchDate.value = e.detail.value
  const date = new Date(e.detail.value)
  formData.value.matchTime = date.getTime()
}

const onStatusChange = (e) => {
  statusIndex.value = e.detail.value
  formData.value.status = parseInt(e.detail.value) + 1
}

const onWinModelChange = (e) => {
  winModelIndex.value = e.detail.value
  formData.value.winModel = parseInt(e.detail.value) + 1
}

const onStartTypeChange = (e) => {
  startTypeIndex.value = e.detail.value
  formData.value.startType = parseInt(e.detail.value)
}

const updateRoom = async () => {
  if (!formData.value.name.trim()) {
    uni.showToast({
      title: '请输入房间名称',
      icon: 'none'
    })
    return
  }
  
  submitting.value = true
  try {
    const result = await MatchRoomAPI.edit({
      matchRoomId: roomId.value,
      matchScheduleId: scheduleId.value,
      name: formData.value.name,
      owner: formData.value.owner,
      matchTime: formData.value.matchTime,
      status: formData.value.status,
      winModel: formData.value.winModel,
      startType: formData.value.startType
    })
    
    if (result.code === 0) {
      uni.showToast({
        title: '更新成功',
        icon: 'success'
      })
      setTimeout(() => {
        goBack()
      }, 1500)
    } else {
      throw new Error(result.msg || '更新失败')
    }
  } catch (error) {
    console.error('更新房间失败:', error)
    uni.showToast({
      title: error.message || '更新失败',
      icon: 'none'
    })
  } finally {
    submitting.value = false
  }
}

const goBack = () => {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.room-edit-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 40rpx;
}

.page-header {
  text-align: center;
  margin-bottom: 60rpx;
  
  .page-title {
    display: block;
    font-size: 48rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 20rpx;
    text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
  }
  
  .page-subtitle {
    font-size: 28rpx;
    color: rgba(255, 255, 255, 0.8);
  }
}

.loading-container {
  text-align: center;
  color: #fff;
  padding: 50rpx;
}

.form-section {
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
  
  .form-item {
    margin-bottom: 30rpx;
    
    .form-label {
      display: block;
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
      margin-bottom: 15rpx;
    }
    
    .form-input {
      width: 100%;
      height: 80rpx;
      padding: 0 20rpx;
      border: 2rpx solid #ddd;
      border-radius: 12rpx;
      font-size: 28rpx;
      background: #fff;
      box-sizing: border-box;
      
      &:focus {
        border-color: #667eea;
      }
    }
    
    .form-picker {
      width: 100%;
      height: 80rpx;
      border: 2rpx solid #ddd;
      border-radius: 12rpx;
      background: #fff;
      box-sizing: border-box;
      
      .picker-text {
        line-height: 80rpx;
        padding: 0 20rpx;
        font-size: 28rpx;
        color: #333;
      }
    }
  }
}

.form-actions {
  display: flex;
  gap: 20rpx;
  
  .cancel-btn, .submit-btn {
    flex: 1;
    height: 80rpx;
    border: none;
    border-radius: 12rpx;
    font-size: 28rpx;
    font-weight: bold;
  }
  
  .cancel-btn {
    background: #f8f9fa;
    color: #666;
    border: 2rpx solid #eee;
  }
  
  .submit-btn {
    background: linear-gradient(135deg, #007bff 0%, #0056b3 100%);
    color: #fff;
    
    &:disabled {
      opacity: 0.6;
    }
  }
}

.loading-spinner {
  width: 60rpx;
  height: 60rpx;
  border: 4rpx solid #f3f3f3;
  border-top: 4rpx solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</style> 